import navToNext from '../../../../wxjs/navToNext.js';
const app = getApp();

var data = {
  xhx_images: app.xhx_images,
  xhx_route: app.xhx_route,
  path: app.xhx_images.challengePostersBg,
  challengeId: null, 
  userId:null,
  awardData:null,
};

var currentPage = {
  data,
  onLoad,
  getFont,
  getSelfDetail,
  getRewardRecord,
  receiveAward,

  newCanvas, //名片生成
  drawBg,
  drawFont,
  setAdress,
  drawHead,
  drawUser,
  
  clickSave,
  canvasToTempFile, //保存到手机

  onShareAppMessage: function () {
    const that = this;
    var userId=null;
    const challengeId = that.data.selfChallengeId;
    // if (selfChallengeId && that.data.awardData && that.data.awardData.status == 0) {
    //   that.receiveAward();
    // }
    return {
      title: '',
      path: `${app.xhx_route.leagueList}`
    }
  }
};

var page = Object.assign({}, navToNext, currentPage);

Page(page)

function onLoad(options) {
  // console.log('=============',options)
  const that = this;
  var challengeId = options.id || '';
  var selfChallengeId = options.uuid || '';

  var sys = wx.getSystemInfoSync();
  var width = sys.windowWidth;
  var height = sys.windowHeight;
  var statusBarHeight = sys.statusBarHeight;

  that.setData({
    challengeId: challengeId,
    selfChallengeId: selfChallengeId,
    width: width,
    height: height,
    statusBarHeight,
    getSize: (new UIToReality(width)).transitionUI
  })
  that.getFont();
  if (challengeId){
    that.getRewardRecord(); 
  } else if (selfChallengeId){
    that.getSelfDetail();
  }
}

// 响应式转换对象(ui750转实际px)
function UIToReality(windowWidth) {
  this.transitionUI = function (size = 750) {
    return size / 750 * windowWidth;
  }
}

function getSelfDetail(){
  const that = this;
  var param = {};
  param.id = that.data.selfChallengeId;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.selfGetDetail,
    data: param,
    cancelToast: true,
    success: function (res) {
      var data=res.data;
      if (!data) {
        return;
      }
      var param={
        rewardAmount: data.matchScheduleInfo.userRewardAmount||0,
        receiveTime:data.matchScheduleInfo.endTime,
        prizeType:4,
        username: data.matchScheduleInfo.username,
        headPortrait: data.matchScheduleInfo.headPortrait || "./avator.jpeg",
        matchSchuduleName: data.matchScheduleInfo.name+'挑战赛',
      }
      that.setData({
        awardData: param
      })
      that.newCanvas();
    },
    fail: function (res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}

// 获取奖励信息
function getRewardRecord() {
  const that = this;
  var param = { tV2MatchScheduleId: that.data.challengeId };
  // param.userId = 466;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.getMatchRewardRecord,
    data: param,
    cancelToast: true,
    success: function (res) {
      console.log(res);
      var data=res.data;
      if (!data){
        return;
      }
      that.setData({
        awardData: data
      })
      that.newCanvas();
    },
    fail: function (res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}
function receiveAward() {
  const that = this;
  var param = { id: that.data.awardData.id };
  app.middleware.requestAjax({
    serAddr: app.serAddrs.addMatchRewardRecord,
    data: param,
    cancelToast: true,
    success: function (res) {
      that.getRewardRecord();
      // app.middleware.showToast("加载失败");
    },
    fail: function (res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}
/**
 * 保存到手机
 */
function clickSave() {
  const that=this;
  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;
  myInfo = app.isNavigateToBind();
  if (!myInfo) return;
  that.canvasToTempFile();
}
function canvasToTempFile() {
  const that=this;
  wx.canvasToTempFilePath({
    x: 0,
    y: 0,
    width: that.data.width,
    height: that.data.height,
    canvasId: 'myCanvas',
    canvas:'',
    success(res) {
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          wx.showToast({
            title: '保存成功',
            duration: 1000
          })
          if (that.data.challengeId && that.data.awardData && that.data.awardData.status==0){
            that.receiveAward();
          }
        }
      })
    }
  })
}

function newCanvas(){
  const that=this;
  var ctx = null;
  ctx = wx.createCanvasContext('myCanvas');
  // ctx.clearRect(0, 0, that.data.width, that.data.height);
  
  that.drawBg(ctx);
  that.drawFont(ctx);
  that.drawHead(ctx);
  that.drawUser(ctx);
  ctx.draw(true, function () {
    console.log('背景绘制完毕111111111111111111111111111111')
  })
}

// 绘制背景图
function drawBg(ctx){
  const that=this;
  var path = that.data.path;
  //这个地方的图片是需要注意，图片需要下载不然，手机上不能正常显示
  ctx.drawImage(path, 0, 0, that.data.width, that.data.height);
  // ctx.draw(true, function () {
  //   console.log('背景绘制完毕')
  // })
}

function drawFont(ctx){
  const that=this;
  ctx.setFillStyle('#ffffff')
  ctx.font = 'normal normal 12px PingFang SC';
  ctx.setFontSize(that.data.getSize(60));
  ctx.setTextBaseline('top');
  var text ='我正在参与谁变健身';
  const titleWidth = ctx.measureText(text).width;
  ctx.fillText(text, that.data.width / 2 - titleWidth / 2, that.data.getSize(160));
  const nameWidth = ctx.measureText(that.data.awardData.matchSchuduleName).width;
  ctx.fillText(that.data.awardData.matchSchuduleName, that.data.width / 2 - nameWidth / 2, that.data.getSize(270));
  
  that.setAdress(ctx);
  // ctx.draw(true, function () {
  //   console.log('背景绘制完毕')
  // })
}

function setAdress(ctx){
  const that=this;
  ctx.setTextBaseline('bottom');

  ctx.setFontSize(that.data.getSize(80));
  var money = ctx.measureText((that.data.awardData.rewardAmount).toString()).width;

  ctx.setFontSize(that.data.getSize(40));
  var getWidth = ctx.measureText('获得').width;
  var awardName = that.data.awardData.prizeType == 1 ? '元超级大奖' : that.data.awardData.prizeType == 2 ? '元幸运大奖' : that.data.awardData.prizeType == 3 ? '元优秀奖' : '现金';
  var awardNameWidth = ctx.measureText(awardName).width;

  var totalWidth = money+getWidth + awardNameWidth + that.data.getSize(16);

  ctx.fillText('获得', that.data.width / 2 - totalWidth / 2, that.data.getSize(455));

  ctx.setFontSize(that.data.getSize(80));
  ctx.setFillStyle('#FFD017');
  ctx.fillText(that.data.awardData.rewardAmount, that.data.width / 2 - totalWidth / 2 + getWidth + that.data.getSize(8), that.data.getSize(465));
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(that.data.getSize(40));
  ctx.fillText(awardName, that.data.width / 2 - totalWidth / 2 + getWidth + money + that.data.getSize(16), that.data.getSize(455));
  // ctx.draw(true, function () {
  //   console.log('背景绘制完毕')
  // })
}

function drawUser(ctx){
  const that = this;
  ctx.drawImage(that.data.xhx_images.qcode, that.data.width - that.data.getSize(200), that.data.height - that.data.getSize(330), that.data.getSize(100), that.data.getSize(100));
  ctx.font = 'normol normol 16px PingFang SC';
  ctx.setTextBaseline('top');
  ctx.setFontSize(that.data.getSize(30));
  ctx.fillText(that.data.awardData.username, that.data.getSize(200), that.data.height - that.data.getSize(310));
  var time='';
  if (that.data.awardData.receiveTime){
    time = that.data.awardData.receiveTime.split(' ')[0];
  }else{
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    time = year + seperator1 + month + seperator1 + strDate;
  }
  ctx.fillText(time, that.data.getSize(200), that.data.height - that.data.getSize(270));
  // ctx.draw(true, function () {
  //   console.log('背景绘制完毕')
  // })
}

function drawHead(ctx){
  const that = this;
  if (!that.data.awardData.headPortrait) return;
  wx.downloadFile({
    url: that.data.awardData.headPortrait,
    success: function (res) {
      // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
      if (res.statusCode === 200) {
        var imgUrl = res.tempFilePath;
        ctx.save();
        ctx.arc(that.data.getSize(130), that.data.height - that.data.getSize(280), that.data.getSize(50), 0, 2 * Math.PI)
        ctx.fill();
        ctx.clip();
        ctx.drawImage(imgUrl , that.data.getSize(80), that.data.height - that.data.getSize(330), that.data.getSize(100), that.data.getSize(100));
        // ctx.drawImage(imgUrl, 160, 160, 50, 50);
        ctx.restore();
        ctx.draw(true, function () {
          console.log('背景绘制完毕')
        });
      }
    }
  })
}

function getFont() {
  wx.loadFontFace({
    family: 'zihun35hao-jindianyahei',
    source: 'url("https://happyfit.oss-cn-shenzhen.aliyuncs.com/font.ttf")',
    success: function (res) {
      // console.log('======================', res.status)
    },
    fail: function (res) {
      // console.log('======================', res.status)
    },
    complete: function (res) {
      // console.log('======================', res.status);
    }
  });
}